﻿///////////////////////////////////////////////////////////////
//                                                           //
// Code from Arcanea Project.                                //
//                                                           //
// Please include this license part to every reproduction    //
//   of code.                                                //
//                                                           //
// This code is under Ms-RL license                          //
//                                                           //
// Please read futher information about the license,         //
//   the project (news and updates) and the                  //
//   contributors on the address :                           //
//     http://www.codeplex.com/Arcanea/                      //
//                                                           //
///////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using Arcanea.NetworkEngine.Abstract.Engines;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Arcanea.NetworkEngine.Concrete.Engines.Serialisation
{
    /// <summary>
    /// Engine de serialisation binaire
    /// </summary>
    public class BinarySerialisationEngine : ISerialisationEngine
    {
        public override byte[] Serialise(object obj)
        {
            try
            {

                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream ms = new MemoryStream();
                bf.Serialize(ms, obj);
                return ms.GetBuffer();
            }
            catch (Exception e)
            {
                logger.Error("Unable to Serialise : " + (obj==null?"null":obj.GetType().ToString()) + " ; " + e.Message);
                return null;
            }
        }

        public override object Deserialise(byte[] array)
        {
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream ms = new MemoryStream(array);
                return bf.Deserialize(ms);
            }
            catch (Exception e)
            {
                logger.Error("Unable to Deserialise " + (array == null ? "null" : array.GetType().ToString()) + " ; " + e.Message);
                return null;
            }
        }
    }
}
